package Designpatterns.shizhan.broker;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CGLIBProxy implements MethodInterceptor {
    private Object target;
    private CGLIBProxy(Object target){
        this.target=target;
    }
    public static BusinessService createProxy(BusinessService target) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(new CGLIBProxy(target));
        return (BusinessService) enhancer.create();
    }
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("Log before executing business logic...");

        // 调用真实业务方法
        Object result = methodProxy.invokeSuper(o, objects);

        // 在业务方法执行后记录日志
        System.out.println("Log after executing business logic...");

        return result;
    }
}
